package com.android.camera2.common.utils;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.hardware.camera2.CameraCharacteristics;
import android.media.ExifInterface;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.OrientationEventListener;

import com.android.camera2.MyApplication;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import static com.android.camera2.common.utils.CameraParameter.FRONT_CAMERA;
import static com.android.camera2.common.utils.CameraParameter.MAIN_CAMERA;

public class CameraUtils {

    private long lastClickTime;
    private static final String TAG = CameraUtils.class.getSimpleName();

    private static final CameraUtils instance = new CameraUtils();

    public static CameraUtils getInstance() {
        return instance;
    }

    private static Context mContext = MyApplication.getApplication();

    private static final String[] STORE_IMAGES = {MediaStore.Images.Thumbnails._ID,};
    private static final String[] STORE_VIDEO = {MediaStore.Video.Thumbnails._ID,};
    public static final String GALLERY_PATH = Environment.getExternalStoragePublicDirectory(Environment
            .DIRECTORY_DCIM) + File.separator + "Camera";
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd_HHmmss");


    /**
     * 添加时间水印
     *
     * @param mBitmap
     * @return mNewBitmap
     */
    public Bitmap AddTimeWatermark(Bitmap mBitmap) {
        //获取原始图片与水印图片的宽与高
        int mBitmapWidth = mBitmap.getWidth();
        int mBitmapHeight = mBitmap.getHeight();
        //定义底片 大小 将mBitmap填充
        Bitmap mNewBitmap = Bitmap.createBitmap(mBitmapWidth, mBitmapHeight, Bitmap.Config.ARGB_8888);
        Canvas mCanvas = new Canvas(mNewBitmap);
        //向位图中开始画入MBitmap原始图片
        mCanvas.drawBitmap(mBitmap, 0, 0, null);
        //添加文字
        Paint mPaint = new Paint();
        String mFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss EEEE").format(new Date());
        //String mFormat = TingUtils.getTime()+"\n"+" 纬度:"+GpsService.latitude+"  经度:"+GpsService.longitude;
        mPaint.setColor(Color.RED);
        mPaint.setTextSize(20);
        //水印的位置坐标
        mCanvas.drawText(mFormat, (mBitmapWidth * 1) / 10, (mBitmapHeight * 14) / 15, mPaint);
//        mCanvas.save(Canvas.ALL_SAVE_FLAG);
        mCanvas.save();
        mCanvas.restore();

        return mNewBitmap;
    }

    /**
     * 处理超时检测  指定时间内被点击次数大于2此则返回true
     *
     * @return
     */
    public boolean doubleClickTimeoutCheck() {
        long currentTimeMillis = System.currentTimeMillis();
        long checkTime = currentTimeMillis - lastClickTime;
        if (0 < checkTime && checkTime < 600) {
            return true;
        }
        lastClickTime = currentTimeMillis;
        return false;
    }


    public static boolean saveBitmap(Bitmap bitmap) {
        boolean success = false;
        String fileName = DATE_FORMAT.format(new Date(System.currentTimeMillis())) + ".jpg";
        File outFile = new File(GALLERY_PATH, fileName);
        Log.d(TAG, "saveImage. filepath: " + outFile.getAbsolutePath());
        FileOutputStream os = null;
        try {
            os = new FileOutputStream(outFile);
            success = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
            LogUtil.i(TAG, "saveBitmap: " + success);
            if (success) {
                Log.i(TAG, "path: " + outFile.getAbsolutePath());
                insertToDB(outFile.getAbsolutePath());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return success;
    }

    private static void insertToDB(String picturePath) {
        ContentValues values = new ContentValues();
        ContentResolver resolver = mContext.getContentResolver();
        values.put(MediaStore.Images.ImageColumns.DATA, picturePath);
        values.put(MediaStore.Images.ImageColumns.TITLE, picturePath.substring(picturePath.lastIndexOf("/") + 1));
        values.put(MediaStore.Images.ImageColumns.DATE_TAKEN, System.currentTimeMillis());
        values.put(MediaStore.Images.ImageColumns.MIME_TYPE, "image/jpeg");
//        values.put(MediaStore.Images.ImageColumns.ORIENTATION, orientation);
        resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    }

    public static void insertVideoToDB(String videoPath) {
        ContentValues values = new ContentValues();
        ContentResolver resolver = mContext.getContentResolver();
        values.put(MediaStore.Video.VideoColumns.DATA, videoPath);
        values.put(MediaStore.Video.VideoColumns.TITLE, videoPath.substring(videoPath.lastIndexOf("/") + 1));
        values.put(MediaStore.Video.VideoColumns.MIME_TYPE, "video/mp4");
//        values.put(MediaStore.Images.ImageColumns.ORIENTATION, orientation);
        resolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
    }


    public static Bitmap getLatestPictureThumbBitmap() {
        Bitmap bitmap = null;
        // 按照时间顺序降序查询
        Cursor cursor = MediaStore.Images.Media.query(mContext.getContentResolver(), MediaStore.Images.Media
                .EXTERNAL_CONTENT_URI, STORE_IMAGES, null, null, MediaStore.Files.FileColumns.DATE_MODIFIED + " DESC");
        boolean first = cursor.moveToFirst();
        if (first) {
            long id = cursor.getLong(0);
            LogUtil.i(TAG, "image_id = " + id);
            bitmap = MediaStore.Images.Thumbnails.getThumbnail(mContext.getContentResolver(), id, MediaStore.Images
                    .Thumbnails.MICRO_KIND, null);
        }
        cursor.close();
        return bitmap;
    }

    public static Bitmap getLatestVideoThumbBitmap() {
        Bitmap bitmap = null;

        Uri originalUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        ContentResolver cr = mContext.getContentResolver();
        Cursor cursor = cr.query(originalUri, STORE_VIDEO, null, null, MediaStore.Files.FileColumns.DATE_MODIFIED + " DESC");
        if (cursor == null) {
            return null;
        }

        boolean first = cursor.moveToLast();
        if (first) {
            long id = cursor.getLong(0);
            LogUtil.i(TAG, "video_id = " + id);
            bitmap = MediaStore.Video.Thumbnails.getThumbnail(mContext.getContentResolver(), id, MediaStore.Video
                    .Thumbnails.MICRO_KIND, null);
        }

        cursor.close();
        return bitmap;
    }


    public static int getRecordingRotation(int orientation,
                                           CameraCharacteristics characteristics) {
        int rotation = -1;
        int sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
        boolean facingFront = characteristics.get(CameraCharacteristics.LENS_FACING)
                == CameraCharacteristics.LENS_FACING_FRONT;
        if (orientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
            if (facingFront) {
                LogUtil.i(TAG, "camera_front");
                rotation = (sensorOrientation - orientation + 360) % 360;
            } else {
                LogUtil.i(TAG, "camera_main");
                rotation = (sensorOrientation + orientation) % 360;
            }
        } else {
            rotation = sensorOrientation;
        }
        return rotation;
    }

    /**
     * has abandoned method
     *
     * @param isMainCamera
     * @param bytes
     * @param orientationDegree
     * @return
     */
    public Bitmap adjustPhotoRotation(boolean isMainCamera, byte[] bytes, final int orientationDegree) {
        Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        Bitmap resBitmap;
        Matrix matrix = new Matrix();
        Matrix submatrix = new Matrix();
        matrix.setRotate(orientationDegree, bitmap.getWidth() / 2, bitmap.getHeight() / 2);

        resBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);

        if (!isMainCamera) {
            submatrix.setScale(-1, 1);
            resBitmap = Bitmap.createBitmap(resBitmap, 0, 0, resBitmap.getWidth(), resBitmap.getHeight(), submatrix, false);
        }

        try {
            return resBitmap;
        } catch (OutOfMemoryError ex) {
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 调整照片
     *
     * @param CurrentCamera cameraid
     * @param data          source data
     * @return bitmap
     */
    public static Bitmap adjustSourcePic(String CurrentCamera, byte[] data) {

        int orientation = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(new ByteArrayInputStream(data));
            int value = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1);
            LogUtil.e(TAG, "values = " + value);
            switch (value) {
                case ExifInterface.ORIENTATION_NORMAL:
                    if (CurrentCamera.equals(MAIN_CAMERA)) {
                        orientation = 90;
                    } else if (CurrentCamera.equals(FRONT_CAMERA)) {
                        orientation = 270;
                    }
                    break;
                case ExifInterface.ORIENTATION_ROTATE_90:
                    orientation = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    if (CurrentCamera.equals(MAIN_CAMERA)) {
                        orientation = 270;
                    } else if (CurrentCamera.equals(FRONT_CAMERA)) {
                        orientation = 90;
                    }
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    orientation = 0;
                    break;

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
        Bitmap calBitmap;
        Matrix rMatrix = new Matrix();
        Matrix nMatrix = new Matrix();

        rMatrix.setRotate(orientation, bitmap.getWidth() / 2, bitmap.getHeight() / 2);
        calBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), rMatrix, false);

        //deal front Mirroring
        if (CurrentCamera.equals(FRONT_CAMERA)) {
            nMatrix.setScale(-1, 1);
            calBitmap = Bitmap.createBitmap(calBitmap, 0, 0, calBitmap.getWidth(), calBitmap.getHeight(), nMatrix, false);
        }

        return calBitmap;
    }

    /**
     * File Path 文件存储路径
     *
     * @param isvideo   是否为视频文件
     * @param timeStamp 文件名
     * @return 文件路径
     */
    public static String getFilePath(boolean isvideo, long timeStamp) {
        File directory;
        String end;
        if (isvideo) {
            directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
            end = ".mp4";
        } else {
            directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            end = ".jpg";
        }
        LogUtil.i(TAG,"file = " + directory + File.separator + timeStamp + end);
        return directory + File.separator + timeStamp + end;

    }


}
